package com.sport.websocket;


import com.google.gson.Gson;
import com.sport.constant.WsResultConstant;
import com.sport.pojo.dto.CampMessageDto;
import com.sport.pojo.vo.SendingMessage;
import com.sport.pojo.vo.WsResult;
import com.sport.service.RoomService;
import com.sport.service.RoomServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/roomws/{id}/{room}")
@Component
public class RoomWs {

    private static final Map<String, Session> onlineUsers = new ConcurrentHashMap<>();
    private static final Map<String, String> messages = new ConcurrentHashMap<>();
    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    /**
     * 建立websocket连接后，被调用
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id, @PathParam("room") String room) {
        //1，将session进行保存
        try {
            onlineUsers.put(id + "&" + room, session);
            RoomServiceImpl roomService = (RoomServiceImpl) applicationContext.getBean(RoomService.class);
            CampMessageDto campMessageDto = roomService.showRoomNumber(room);
            String s = new Gson().toJson(new WsResult(WsResultConstant.SHOW_ALL_PEOPLE, "展示人员", new Gson().toJson(campMessageDto)));
            //2，发送消息
            if (messages.get(room) != null) {
                System.out.println(messages.get(room));
                String msg = new Gson().toJson(new WsResult(WsResultConstant.ADD_MESSAGE, "增加的消息", messages.get(room)));
                //2，发送消息
                session.getBasicRemote().sendText(msg);
            }
            session.getBasicRemote().sendText(s);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void broadcast(String roomId, String UandR) {
        try {
            //遍历map集合
            Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
            System.out.println(entries.size());
            for (Map.Entry<String, Session> entry : entries) {
                if (isConRoom(entry.getKey(), roomId)) {
                    Session session = entry.getValue();
                    //发送消息
                    session.getBasicRemote().sendText(UandR);
                }
            }
        } catch (Exception e) {
            //记录日志
        }
    }

    public boolean isConId(String key, String id) {
        if (key.substring(0, key.indexOf("&")).equals(id)) {
            return true;
        }
        return false;
    }

    public boolean isConRoom(String key, String room) {
        if (key.substring(key.indexOf("&") + 1).equals(room)) {
            return true;
        }
        return false;
    }

    public void broadcastKickUser(String roomId, String id, String host, String UandR) {
        try {
            //遍历map集合
            Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
            System.out.println(entries.size());
            for (Map.Entry<String, Session> entry : entries) {
                if (isConRoom(entry.getKey(), roomId)) {
                    if (!isConId(entry.getKey(), id)) {
                        Session session = entry.getValue();
                        session.getBasicRemote().sendText(UandR);
                    } else {
                        Session session = entry.getValue();
                        session.getBasicRemote().sendText(new Gson().toJson(new WsResult(WsResultConstant.YOU_KiCK, "你被踢出房间", null)));
                    }
                }
            }
        } catch (Exception e) {
            //记录日志
        }
    }

    /**
     * 浏览器发送消息到服务端，该方法被调用
     * <p>
     * 张三  -->  李四
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        try {
            SendingMessage msg = new Gson().fromJson(message, SendingMessage.class);
            if(messages.get(msg.getRoomId())==null){
                //防止拼接null
                messages.put(msg.getRoomId(),"");
            }
            messages.put(msg.getRoomId(),messages.get(msg.getRoomId())+msg.getMessage()+"\n");
            String s = new Gson().toJson(new WsResult(WsResultConstant.ADD_MESSAGE,"增加的消息", msg.getMessage()));
            broadcast(msg.getRoomId(),s);
        } catch (Exception e) {
        }
    }

    /**
     * 断开 websocket 连接时被调用
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session, @PathParam("id") String id, @PathParam("room") String room) {
        //1,从onlineUsers中剔除当前用户的session对象
        onlineUsers.remove(id + "&" + room);
        System.out.println(id + "-" + room + "下线");
//            //2,通知其他所有的用户，当前用户下线了
//            String message = MessageUtils.getMessage(true,null,getFriends());
//            broadcastAllUsers(message);
    }

}
